<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="tableData">
        <!-- 放置列 -->
        <el-table-column align="center" width="200" label="角色">
          <!-- {row} 是 scope 结构出来的   相当于tableData 数组 -->
          <template slot-scope="{row}">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.name"
            />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <!-- slot-scope  老式语法 -->
          <template slot-scope="{row}">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              size="mini"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>
              {{ row.state === 1 ? '已启用' : '未启用' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述">
          <template slot-scope="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="200"
          align="center"
        >
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <el-button type="text" size="small" @click="hOk(row)">确认</el-button>
              <el-button type="text" size="small" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="small" @click="hAssign(row.id)">分配权限</el-button>
              <el-button type="text" size="small" @click="hEdit(row)">编辑</el-button>
              <el-popconfirm
                confirm-button-text="好的"
                cancel-button-text="不用了"
                icon="el-icon-info"
                icon-color="red"
                title="确定删除？"
                @onConfirm="hDel(row.id)"
              >
                <el-button slot="reference" type="text" size="small">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          :total="total"
          :background="true"
          layout=" prev, pager, next, sizes"
          :current-page="page"
          :page-sizes="[5,10,15,20,30]"
          :page-size="pagesize"
          @size-change="handleSizeChange"
          @current-change="hCurrentChange"
        />
      </el-row>
    </div>
    <!-- 添加  弹出框 -->
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog">
      <!-- 表单内容 -->
      <el-form ref="formData" label-width="120px" :model="formData" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch
            v-model="formData.state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            size="mini"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="add">确定</el-button>
              <el-button size="mini" @click="hClose">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <assign-permission ref="refPerm" :show-dialog-perm.sync="showDialogPerm" :cod-id="codId" />
  </div>
</template>
<script>
import { addRoles, getRoles, updateRole, delRole } from '@/api/role'
import assignPermission from './components/assignPermission.vue'
export default {
  name: 'Role',
  components: { assignPermission },
  data() {
    return {
      // id
      codId: 0,
      // 权限弹窗
      showDialogPerm: false,
      // 表格所用
      total: 0,
      page: 1,
      pagesize: 5,
      tableData: [],
      // 添加表单所用属性
      showDialog: false,
      formData: {
        name: '',
        state: 1,
        description: ''
      },
      // 表单校验  prop
      rules: {
        name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    hAssign(id) {
      this.codId = id
      this.showDialogPerm = true
      this.$nextTick(() => {
        this.$refs.refPerm.getPermUser()
      })
    },
    // 删除角色
    hDel(id) {
      delRole(id)
      this.$message.success('删除成功')
      if (this.tableData.length === 1) {
        if (this.page > 1) {
          this.page--
        }
      }
      this.loadRoles()
    },
    // 修改数据发送到服务器
    hOk(row) {
      if (!row.editRow.name || !row.editRow.description) return this.$message.warning('此项必填!!!!')
      updateRole(row.editRow)
      this.$message.success('修改成功!!')
      row.isEdit = false
      this.loadRoles()
    },
    // 改成编辑状态
    hEdit(row) {
      row.isEdit = true
    },
    // 关闭模态框   清空表单
    hClose() {
      this.showDialog = false
      this.$refs.formData.resetFields()
      // 更新表格数据
      // 想要看到刚才添加的数据，要跳转到最后一页
      // Math.ceil  向上取值
      this.total = this.total + 1
      this.page = Math.ceil(this.total / this.pagesize)
      this.loadRoles()
    },
    // 添加角色
    async addRoles() {
      await addRoles(this.formData)
      this.$message.success('添加成功')
      this.hClose()
    },
    // 表单托底校验
    add() {
      this.$refs.formData.validate(valid => {
        valid && this.addRoles()
      })
    },
    // 改变每页显示数量
    handleSizeChange(val) {
      this.pagesize = val
      this.page = 1
      this.loadRoles()
    },
    // 分页点击切换
    hCurrentChange(page) {
      this.page = page
      this.loadRoles()
    },
    // 获取角色
    async loadRoles() {
      const res = await getRoles({ page: this.page, pagesize: this.pagesize })
      // console.log(res)
      this.tableData = res.data.rows
      this.total = res.data.total
      // 给每一行都补充一个属性:  isEdit,  用来标记当前是否处于编辑状态
      this.tableData.forEach(item => {
        // this.$set(对象,新添加的属性名,属性值)
        // 这样补充的属性是响应式的
        this.$set(item, 'isEdit', false)
        // 补充一个缓存数据
        this.$set(item, 'editRow', {
          id: item.id,
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    }
  }
}
</script>

<style scoped>
.role-operate {
  padding: 10px;
}
</style>
